<script lang="ts" setup>
import { appModel } from '@/api/app';
import { Add28Filled, Delete16Regular } from '@vicons/fluent';
import { computed, ref, watch } from 'vue';

interface Props {
  limit: number;
}
const props = withDefaults(defineProps<Props>(), {
  limit: 9
});
const modelValue = defineModel('value');
const fileList = ref([]);

if(Array.isArray(modelValue.value)) {
  fileList.value = modelValue.value;
} else {
  fileList.value = modelValue.value ? [modelValue.value] : [];
}

watch(fileList.value, () => {
  if(Array.isArray(modelValue.value)) {
    modelValue.value = fileList.value;
  } else {
    modelValue.value = fileList.value[0] || '';
  }
});

async function fileChange(e) {
  const file = e.target.files[0];
  const { data: { data: fileUrl } } = await appModel.upload(file);
  fileList.value.push(fileUrl);

  e.target.value = null;
}

const hasAddBtn = computed(() => {
  if(!Array.isArray(modelValue.value) && fileList.value.length) {
    return false;
  }
  if(Array.isArray(modelValue.value) && fileList.value.length >= props.limit) {
    return false;
  }
  return true;
});
</script>
<template>
  <div>

      <input
        class="hidden"
        id="upload"
        type="file"
        @change="fileChange"
      >
      <div
        class="flex gap-mini flex-wrap"
      >
        <div
          class="w-120px h-120px rounded-8px overflow-hidden relative"
          v-for="img, idx in fileList"
          :key="idx"
        >
          <img
            class="
              w-full
              h-full
              max-w-full
              max-h-full
              object-contain
            "
            :src="img"
          >
          <div
            class="
              absolute
              top-0
              right-0
              z-10
              bg-gray-4
              bg-op-40
              rounded-50%
              w-70px
              h-70px
              transform-translate-y--50%
              transform-translate-x-50%
              c-white
              hover:bg-gray
              hover:c-red
            "
            @click="fileList.splice(idx, 1)"
          >
            <NIcon
              class="absolute! bottom-10px left-10px"
              size="20"
            >
              <Delete16Regular />
            </NIcon>
          </div>
        </div>
        <label for="upload" v-if="hasAddBtn">
          <div
            class="
              inline-flex
              w-120px
              h-120px
              rounded-8px
              b-dashed
              b-#ccc
              c-#ccc
              border-width-2px
              justify-center
              items-center
              hover:b-primary
              hover:c-primary
            "
          >
            <NIcon
              size="36"
            >
              <Add28Filled />
            </NIcon>
          </div>
        </label>
      </div>
  </div>
</template>
